package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@WebServlet("/getOrders")
public class GetOrdersServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();

            // 创建 DB_Order 实例
            User Order = (User) request.getSession().getAttribute("user");

            // 这里可以根据需求添加查询条件
            List<String> input = new ArrayList<>();
            List<String> orders = Order.Historical_orders(input);

            // 构建 JSON 响应
            StringBuilder jsonResponse = new StringBuilder();
            jsonResponse.append("{\"orders\":[");
            for (int i = 0; i < orders.size(); i++) {
                String[] orderFields = orders.get(i).split(",");
                jsonResponse.append("{");
                jsonResponse.append("\"oid\":\"").append(orderFields[0]).append("\",");
                jsonResponse.append("\"uid\":\"").append(orderFields[1]).append("\",");
                jsonResponse.append("\"aid\":\"").append(orderFields[2]).append("\",");
                jsonResponse.append("\"time\":\"").append(orderFields[3]).append("\",");
                jsonResponse.append("\"payamount\":\"").append(orderFields[4]).append("\",");
                jsonResponse.append("\"state\":\"").append(orderFields[5]).append("\"");
                jsonResponse.append("}");
                if (i < orders.size() - 1) {
                    jsonResponse.append(",");
                }
            }
            jsonResponse.append("]}");

            out.print(jsonResponse.toString());
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}